using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AtCareApplication
{
    public partial class Form1 : Form
    {
        private string mealCodeValue = "";
        private string guestMealCodeValue = "";
        private string specialMealCodeValue = "";
        private string residentIdValue = "";
        private string numberOfMealsValue = "";
        private string amountValue = "";
        private bool amountValueSelected = false;
        private string locationValue = "";
        ScannerApplication scannerApplication = new ScannerApplication();
        
        public Form1()
        {
            InitializeComponent();   
        }

        private void textBox1_pressKey(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            // Determine whether the keystroke is a number from the top of the keyboard.
            if (e.KeyCode == Keys.F1)
            {
                switch (currentPanel){
                    case MAINSCREEN:
                        showPasswordScreen();
                        break;
                    case MENUSCREEN:
                        showMealCodeScreen();
                        break;
                    case RESIDSCREEN:
                        if(resIdTextBox){
                            if (!residentIdValue.Equals("")){
                                textBox4.Text = residentIdValue;
                            }
                        }else{
                            showGuestMealCodeScreen();
                        }
                        break;
                    case REVIEWDATASCREEN:
                        showPreviousData();
                        break;
                    case COUNTANDAMOUNT:
                        currentPanel = SPECIALMEALCODESCREEN;
                        showSecondLineOnSpecialMealCodeScreen("count");
                        displayErrorMessage("Valid #Meals 1 or 2");
                        break;
                    case TRANSFERFILESCREEN:
                        displayErrorMessage("The file was transfered succesfully"); // add some mechanics behind this
                        scannerApplication.transferDataToFile();
                        break;
                }
            }else if (e.KeyCode == Keys.F2){
                switch (currentPanel){
                    case MAINSCREEN:
                        showMenuScreen();
                        break;
                    case MENUSCREEN:
                        showReviewDataScreen();
                        break;
                    case DATETIMESCREEN:
                        showLocationScreen();
                        break;
                    case RESIDSCREEN:
                        if (resIdTextBox){
                            showReviewDataScreen();
                        }else{
                            showSpecialMealCodeScreen();
                        }
                        break;
                    case REVIEWDATASCREEN:
                        showNextData();
                        break;
                    case COUNTANDAMOUNT:
                        currentPanel = SPECIALMEALCODESCREEN;
                        showSecondLineOnSpecialMealCodeScreen("amount");
                        break;
                }
            }else if (e.KeyCode == Keys.F3){
                switch (currentPanel){
                    case REVIEWDATASCREEN:
                        deleteCurrentData();
                        break;
                    case MENUSCREEN:
                        showTransferFileScreen();
                        break;
                }
            }else if (e.KeyCode == Keys.Escape){
                switch (currentPanel){
                    case PASSWORDSCREEN:
                        showMainScreen();
                        break;
                    case MEALCODESCREEN:
                        showMenuScreen();
                        break;
                    case MENUSCREEN:
                        showMainScreen();
                        break;
                    case REVIEWDATASCREEN:
                        showMenuScreen();
                        break;
                    case DATETIMESCREEN:
                        showMainScreen();
                        break;
                    case RESIDSCREEN:
                        showMenuScreen();
                        break;
                    case COUNTANDAMOUNT:
                        showMenuScreen();
                        break;
                    case GUESTMEALCODESCREEN:
                        showMenuScreen();
                        break;
                    case SPECIALMEALCODESCREEN:
                        showMenuScreen();
                        break;
                    case LOCATIONSCREEN:
                        showMainScreen();
                        break;
                    case TRANSFERFILESCREEN:
                        clearErrorMessage();
                        showMainScreen();
                        break;
                }
            }else if (e.KeyCode == Keys.Enter){
                switch (currentPanel){
                    case PASSWORDSCREEN:
                        validatePassword();
                        break;
                    case DATETIMESCREEN:
                        showLocationScreen();
                        break;
                    case MEALCODESCREEN:
                        mealCodeValue = dlTextBox1.Text;
                        if(validateMealCode(mealCodeValue)){
                            showResIdScreen();
                        }else{
                            mealCodeValue = "";
                            displayErrorMessage("Invalid meal code. Range 00-99");
                            dlTextBox1.Text = "";
                            dlTextBox1.Focus();
                        }
                        break;
                    case LOCATIONSCREEN:
                        locationValue = textBox2.Text;
                        label4.Text = locationValue;
                        showMainScreen();
                        break;
                    case RESIDSCREEN:
                        if (resIdTextBox){
                            textBox5.Text = "";
                            resIdTextBox = false;
                            if (validateResId()){
                                residentIdValue = textBox4.Text;
                                displayErrorMessage("Valid #Meals 1 or 2");
                            }else{
                                displayErrorMessage("Invalid ResId");
                            }
                        }else{
                            if (validateNumberOfMeals(textBox5)){
                                scannerApplication.saveValuesToTheDatabase(mealCodeValue, residentIdValue, numberOfMealsValue, amountValue);
                            }else{
                                displayErrorMessage("Invalid number of meals");
                                textBox5.Text = "";
                                textBox5.Focus();
                            }
                        }
                        break;
                    case GUESTMEALCODESCREEN:
                        if(ifGuestMealcodeTextBox){
                            if(validateGuestMealCode()){
                                mealCodeValue = dlTextBox7.Text;
                                textBox8.Text = "";
                                textBox8.Focus();          
                            }else{
                                dlTextBox7.Text = "";
                                dlTextBox7.Focus();
                                displayErrorMessage("Invalid Meal Code. Range 00-99");
                            }
                        }else{
                            if(validateNumberOfMeals(textBox8)){
                                numberOfMealsValue = textBox8.Text;

                                scannerApplication.saveValuesToTheDatabase(mealCodeValue, residentIdValue, numberOfMealsValue, amountValue);
                                showResIdScreen();
                            }else{
                                textBox8.Text = "";
                                textBox8.Focus();
                                displayErrorMessage("Invalid #meals. Range 1-2");
                            }
                        }
                        break;
                    case SPECIALMEALCODESCREEN:
                        if(ifSpecialMealcodeTextBox){
                            if (validateSpecialMealCode()){
                                ifSpecialMealcodeTextBox = false;
                                mealCodeValue = textBox9.Text;
                                showSpecialCodesCountAndAmountScreen();
                            }else{
                                displayErrorMessage("Invalid meal code. Range 00-99");
                            }
                        }else{
                            if (validateSpecialAmountCount()){
                                if (amountValueSelected){
                                    amountValue = dlTextBox2.Text;
                                }else{
                                    mealCodeValue = dlTextBox2.Text;
                                }
                                showResIdScreen();
                            } 
                        }
                        break;
                }
            }
        }

        // for where the date is being changed
        private void textBox2_pressKey(object sender, System.Windows.Forms.KeyEventArgs e){
            char valueInChar = Convert.ToChar(e.KeyValue);
            string valueInString = "" + valueInChar;
            if (e.KeyCode == Keys.Escape){
                showMainScreen();
            }else if (e.KeyCode == Keys.Enter){
                if (textboxvalue.Length == 8){
     
                }else{
                    //show error message saying that the date is not in the valid format
                }
            }else if (System.Text.RegularExpressions.Regex.IsMatch(valueInString, "\\d+")){
                if(textboxvalue.Length == 2 || textboxvalue.Length == 5){

                }else if(textboxvalue.Length == 8){
                    //do nothing or throw an error at the bottom
                }else{
                }
            }
        }

        //for when the time is being changed
        private void textBox3_pressKey(object sender, System.Windows.Forms.KeyEventArgs e){
            string textboxvalue = textBox2.Text;
            char valueInChar = Convert.ToChar(e.KeyValue);
            string valueInString = "" + valueInChar;
            if (e.KeyCode == Keys.Escape){
                showMainScreen();
                //data is not saved.
            }else if (e.KeyCode == Keys.Enter){
                if (textboxvalue.Length == 8){
                    validateTimeAndSaveToSystem();
                }else{
                    //show error message saying that the date is not in the valid format
                }
            }else if (System.Text.RegularExpressions.Regex.IsMatch(valueInString, "\\d+")){
                if (textboxvalue.Length == 2 || textboxvalue.Length == 5){
                }else if (textboxvalue.Length == 8){
                    //do nothing or throw an error at the bottom
                }
                else{
                }
            }
        }

        private void validateTimeAndSaveToSystem(){
            string timeString = textBox2.Text;
            string hours  = timeString.Substring(0,2);
            string minutes = timeString.Substring(4, 2);
            string seconds = timeString.Substring(7, 2);
            int hoursInInteger = Convert.ToInt32(hours);
            int minutesInInteger = Convert.ToInt32(minutes);
            int secondsInInteger = Convert.ToInt32(seconds);
            bool validValue = true;

            if(hoursInInteger < 0 && hoursInInteger > 24){
                // show error
                validValue = false;
            }

            if (minutesInInteger < 0 && minutesInInteger > 60){
                // show error
                validValue = false;
            }

            if (secondsInInteger < 0 && secondsInInteger > 60){
                // show error
                validValue = false;
            }

            if (validValue){
                //save the time value
            }
        }

        private void showGuestMealCodeScreen()
        {
            dlTextBox7.Text = "";
            textBox8.Text = "";
            ifGuestMealcodeTextBox = true;
            clearErrorMessage();
            dlTextBox7.Focus();
            showPanel(GUESTMEALCODESCREEN);
            currentPanel = GUESTMEALCODESCREEN;
        }


        private bool validateResId()
        {
            string resId = textBox4.Text;
            int resIdLength = resId.Length;
            //find the correct resId 
            if (resIdLength < 7 && resIdLength != 0){
                //save the resId and focus on textBox4
                resIdTextBox = false;
                updateLabelText(label41, "F1 = Guest Meals\r\nF2 = Special Codes\r\nEsc = Clear/Exit");
                textBox5.Focus();
                return true;
            }else{
                //display invalid resid
                displayErrorMessage("Invalid Resident Id");
                textBox4.Text = "";
                textBox4.Focus();
                return false;
            }
        }

        private void updateLabelText(Label label, String text){
            label.Text = text;
        }

        private bool validateNumberOfMeals(TextBox textBox){
            //for when enter pressed when on meals text box
            string numberOfMeals = textBox.Text;
            int numberOfMealsLength = numberOfMeals.Length;

            if (numberOfMealsLength == 1 && (numberOfMeals.Equals("1") || numberOfMeals.Equals("2"))){
                //save the value and proceed to the next page
                numberOfMealsValue = textBox.Text;
                textBox4.Text = "";
                textBox5.Text = "";
                dlTextBox7.Text = "";
                textBox.Text = "";
                resIdTextBox = true;
                updateLabelText(label41, "F1 =  Duplicate\r\nF3 =  Review Data\r\nEsc = Exit");
                showResIdScreen();
                return true;
                //previousResIdValue = saved resid field  
            }else{
                displayErrorMessage("Invalid #Meals. Range 1-2");
            }
            return false;
        }

        private void showSecondLineOnSpecialMealCodeScreen(string value){
            if (value.Equals("count")){
                label58.Text = "#Meals=";
                amountValueSelected = false;
                showSpecialMealCodeScreen();
                textBox9.Text = mealCodeValue;
                ifSpecialMealcodeTextBox = false;
                dlTextBox2.Focus();
            }else if(value.Equals("amount")){
                label58.Text = "Amount=";
                amountValueSelected = true;
                showSpecialMealCodeScreen();
                ifSpecialMealcodeTextBox = false;
                dlTextBox2.Focus();
            }   
        }

        private bool validateSpecialAmountCount(){
            if(amountValueSelected){
                if (dlTextBox2.Text.Length > 0){
                    return true;
                }
            }else{
                if(validateNumberOfMeals(dlTextBox2)){
                    return true;
                }
            }
            return false;
        }

        private bool validateSpecialMealCode(){
            String specialMealCode = textBox9.Text;
            if (specialMealCode.Length > 0)
            {
                int specialMealCodeNumber = Convert.ToInt16(specialMealCode);
                if (specialMealCode.Length == 2)
                {
                    if (specialMealCodeNumber >= 0 && specialMealCodeNumber < 100)
                    {
                        mealCodeValue = textBox9.Text;
                        ifSpecialMealcodeTextBox = false;
                        return true;
                    }
                }
            }
            return false;
        }

        private bool validateGuestMealCode(){
            string guestMealCode = dlTextBox7.Text;
            if (guestMealCode.Length > 0)
            {
                int guestMealCodeNumber = Convert.ToInt16(guestMealCode);
                if (guestMealCode.Length == 2)
                {
                    if (guestMealCodeNumber >= 0 && guestMealCodeNumber < 100)
                    {
                        label49.Text = "#Meals=";
                        ifGuestMealcodeTextBox = false;
                        return true;
                    }
                }
            }
            return false;
        }

        private bool validateMealCode(string mealCode){
            if (mealCode.Length > 0)
            {
                int mealCodeInteger = Convert.ToInt16(mealCode);
                if (mealCode.Length == 2)
                {
                    if (mealCodeInteger >= 0 && mealCodeInteger < 100)
                    {
                        return true;
                    }
                }
            }
            return false;
        }


        private bool checkDateFormat(String date){
            //return true for now
            return true;
        }

        private void validatePassword(){
            String enteredPassword = passwordField.Text;
            if (enteredPassword.Equals("911")){
                showDateTimeScreen();
            }else{
                showMainScreen();
            }
        }

        private void showMainScreen(){
            clearErrorMessage();
            label4.Text = locationValue;
            label3.Text = getSystemDate();
            showPanel(MAINSCREEN);
            //showDateTimeOnMainScreen();
            passwordField.Focus();
            currentPanel = MAINSCREEN;
        }

        private string getSystemDate(){
            DateTime today = DateTime.Today;
            return today.ToString("d");
        }

        private void showTimeScreen(){
            clearErrorMessage();
            showPanel(TIMESCREEN);
            textBox3.Focus();
            currentPanel = TIMESCREEN;
        }

        private void showResIdScreen(){
            amountValue = "";
            clearErrorMessage();
            resIdTextBox = true;
            showPanel(RESIDSCREEN);
            textBox4.Text = "";
            textBox5.Text = "";
            textBox4.Focus();
            currentPanel = RESIDSCREEN;
            Meals lastData = scannerApplication.getLastData();

            if (lastData != null)
            {
                label32.Text = lastData.getMealCode() + "," + lastData.getResId() + "," +
                    lastData.getMeals() + "," + lastData.getAmount() + "," + lastData.getDate() + "," + lastData.getTime();
            }
            else
            {
                label32.Text = "No data";
            }
        }

        private void showSpecialCodesCountAndAmountScreen(){
            clearErrorMessage();
            showPanel(COUNTANDAMOUNT);
            currentPanel = COUNTANDAMOUNT;
            textBox9.Focus();
        }

        private void showSpecialMealCodeScreen(){
            ifSpecialMealcodeTextBox = true;
            textBox9.Text = "";
            dlTextBox2.Text = "";
            textBox9.Focus();
            clearErrorMessage();
            showPanel(SPECIALMEALCODESCREEN);
            currentPanel = SPECIALMEALCODESCREEN;
        }


        private void showLocationScreen(){
            clearErrorMessage();
            showPanel(LOCATIONSCREEN);
            currentPanel = LOCATIONSCREEN;
            textBox2.Text = "";
            textBox2.Focus();
        }

        private void showReviewDataScreen(){
            clearErrorMessage();
            if (scannerApplication.getTotalDataCount() == 0){
                displayErrorMessage("No data to show");
            }else{
                Meals meal = scannerApplication.getNextData();
                if (meal == null){
                    //
                }else{
                    showMealOnReviewDataScreen(meal);
                }
                showPanel(REVIEWDATASCREEN);
                currentPanel = REVIEWDATASCREEN;
            }
        }

        private void showTransferFileScreen()
        {
                clearErrorMessage();
                showPanel(TRANSFERFILESCREEN);
            
        }

        private void showNextData()
        {
                Meals meal = scannerApplication.getNextData();
                showMealOnReviewDataScreen(meal);
        }

        private void showPreviousData()
        {
                Meals meal = scannerApplication.getPreviousData();
                showMealOnReviewDataScreen(meal);
        }

        private void deleteCurrentData()
        {
            int totalCount = scannerApplication.getTotalDataCount();
            Console.WriteLine(totalCount);
            if (totalCount > 1){
                scannerApplication.deleteCurrentIndex();
                showNextData();
            }else{
                scannerApplication.deleteCurrentIndex();
                showMainScreen();
                displayErrorMessage("No More Data to Show");
            }
        }

        private void showMealOnReviewDataScreen(Meals meal)
        {
            clearErrorMessage();
            label27.Text = scannerApplication.getCurrentDataNumber().ToString() + " of " + scannerApplication.getTotalDataCount();
            label20.Text = meal.getMealCode();
            label21.Text = meal.getResId();
            label22.Text = meal.getMeals();
            label23.Text = meal.getAmount();
            label24.Text = meal.getDate(); 
            label25.Text = meal.getTime(); 
        }

        private void showMenuScreen()
        {
            clearErrorMessage();
            showPanel(MENUSCREEN);
            currentPanel = MENUSCREEN;
        }

        private void showMealCodeScreen()
        {
            clearErrorMessage();
            dlTextBox1.Text = "";
            showPanel(MEALCODESCREEN);
            dlTextBox1.Focus();
            currentPanel = MEALCODESCREEN;
        }

        private void showPasswordScreen()
        {
            passwordField.Text = "";
            clearErrorMessage();
            showPanel(PASSWORDSCREEN);
            passwordField.Focus();
            currentPanel = PASSWORDSCREEN;
        }

        private void showDateTimeScreen()
        {
            clearErrorMessage();
            showPanel(DATETIMESCREEN);
            //dateTimeField.Focus();
            currentPanel = DATETIMESCREEN;
        }

        private void laser1_GoodReadEvent(datalogic.datacapture.ScannerEngine sender){
            if (currentPanel == MEALCODESCREEN){
                dlTextBox1.Text = sender.BarcodeDataAsText;
                mealCodeValue = dlTextBox1.Text;
                if (validateMealCode(mealCodeValue)){
                    textBox4.Text = "";
                    textBox5.Text = "";
                    dlTextBox1.Text = "";
                    showResIdScreen();
                }else{
                    displayErrorMessage("Invalid meal code. Range 00-99");
                    dlTextBox1.Focus();
                }
            }else if(currentPanel == GUESTMEALCODESCREEN){
                if (ifGuestMealcodeTextBox){
                    dlTextBox7.Text = sender.BarcodeDataAsText;
                    if(validateGuestMealCode()){
                        guestMealCodeValue = dlTextBox7.Text;
                        ifGuestMealcodeTextBox = false;
                        displayErrorMessage("Valid #Meals 1 or 2");
                        textBox8.Focus();
                    }else{
                        displayErrorMessage("Invalid MealCode");
                        dlTextBox7.Text = "";
                        dlTextBox7.Focus();
                    }
                }else{
                    textBox8.Text = sender.BarcodeDataAsText;
                    if (validateNumberOfMeals(textBox8))
                    {
                        numberOfMealsValue = textBox8.Text;
                        scannerApplication.saveValuesToTheDatabase(guestMealCodeValue, residentIdValue, numberOfMealsValue, amountValue);
                        showResIdScreen();
                    }
                    else
                    {
                        displayErrorMessage("Invalid #Meals. Range 1-2");
                        textBox8.Text = "";
                        textBox8.Focus();
                    }
                }
            }else if(currentPanel == SPECIALMEALCODESCREEN){
                if (ifSpecialMealcodeTextBox)
                {
                    textBox9.Text = sender.BarcodeDataAsText;
                    if (validateSpecialMealCode())
                    {
                        specialMealCodeValue = textBox9.Text;
                        ifSpecialMealcodeTextBox = false;
                        showSpecialCodesCountAndAmountScreen();
                    }
                    else
                    {
                        displayErrorMessage("Invalid MealCode");
                        textBox9.Text = "";
                        textBox9.Focus();
                    }
                }else{
                    dlTextBox2.Text = sender.BarcodeDataAsText;
                    if (validateSpecialAmountCount())
                    {
                        if (amountValueSelected)
                        {
                            amountValue = dlTextBox2.Text;
                            scannerApplication.saveValuesToTheDatabase(specialMealCodeValue, residentIdValue, numberOfMealsValue, amountValue);
                        }
                        else
                        {
                            numberOfMealsValue = dlTextBox2.Text;
                            scannerApplication.saveValuesToTheDatabase(specialMealCodeValue, residentIdValue, numberOfMealsValue, amountValue);
                        }
                    }
                    else
                    {
                        if (amountValueSelected)
                        {
                            displayErrorMessage("Invalid amount");
                            
                        }
                        else
                        {
                            displayErrorMessage("Invalid count");
                        }
                        dlTextBox2.Text = "";
                        dlTextBox2.Focus();
                    }
                }
  
            }else if(currentPanel == RESIDSCREEN){
                if (resIdTextBox){
                    textBox4.Text = sender.BarcodeDataAsText;
                    if (validateResId())
                    {
                        residentIdValue = textBox4.Text;
                        resIdTextBox = false;
                        displayErrorMessage("Valid #Meals 1 or 2");
                        textBox5.Focus();
                    }else{
                        displayErrorMessage("Invalid Resident Id");
                        textBox4.Text = "";
                        textBox4.Focus();
                    }
                }else{
                    textBox6.Text = sender.BarcodeDataAsText;
                    if (validateNumberOfMeals(textBox5)){
                        numberOfMealsValue = textBox5.Text;
                        scannerApplication.saveValuesToTheDatabase(mealCodeValue, residentIdValue, numberOfMealsValue, amountValue);
                        textBox4.Text = ""; 
                        textBox5.Text = ""; 
                        textBox5.Focus();
                    }else{
                        displayErrorMessage("Invalid #Meals. Range 1-2");
                        textBox5.Text = "";
                        textBox5.Focus();
                    }
                }
            }
        }

        private void displayErrorMessage(String errorMessage){
            displayLabel.Text = errorMessage;
        }

        private void clearErrorMessage(){
            displayLabel.Text = "";
        }

        private void panel10_GotFocus(object sender, EventArgs e)
        {

        }

        private void label41_ParentChanged(object sender, EventArgs e)
        {

        }

        private void label26_ParentChanged(object sender, EventArgs e)
        {

        }

        private void label14_ParentChanged(object sender, EventArgs e)
        {

        }

        private void label28_ParentChanged(object sender, EventArgs e)
        {

        }

        private void label5_ParentChanged(object sender, EventArgs e)
        {

        }
    }
}